#!/bin/bash
# 邮件系统统一管理脚本 (基于 Screen)
# 功能：基于 screen 会话管理主程序和同步服务
# 用法: ./run_shell.sh [python解释器路径] [命令]
#   例如: ./run_shell.sh python3
#         ./run_shell.sh /www/server/pyporject_evn/versions/3.12.4/bin/python3
#         ./run_shell.sh python3 start-all  # 直接启动所有服务
#         ./run_shell.sh python3 stop-all   # 直接停止所有服务
#         ./run_shell.sh python3 status     # 查看服务状态

# 动态获取项目目录（脚本所在目录）
PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"

# Python解释器路径（支持命令行参数或环境变量或默认值）
if [ -n "$1" ] && [ "$1" != "start-all" ] && [ "$1" != "stop-all" ] && [ "$1" != "restart-all" ] && [ "$1" != "status" ]; then
    PYTHON="$1"
    COMMAND="$2"
elif [ -n "$PYTHON_INTERPRETER" ]; then
    PYTHON="$PYTHON_INTERPRETER"
    COMMAND="$1"
else
    PYTHON=$(which python3)
    COMMAND="$1"
fi

# 脚本路径
MAIN_SERVER_SCRIPT="$PROJECT_DIR/run/start_server.py"
SYNC_SERVER_SCRIPT="$PROJECT_DIR/run/start_sync.py"

# Screen 会话名称
MAIN_SESSION="mail_server"
SYNC_SESSION="mail_sync"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印消息
print_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
print_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
print_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
print_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# 检查Python版本是否>=3.11
check_python_version() {
    local python_cmd=$1
    
    # 检查Python是否存在
    if ! command -v "$python_cmd" &> /dev/null && [ ! -f "$python_cmd" ]; then
        print_error "Python解释器不存在: $python_cmd"
        return 1
    fi
    
    # 获取Python版本
    local version_output=$("$python_cmd" --version 2>&1)
    local version=$(echo "$version_output" | grep -oP '\d+\.\d+\.\d+' | head -1)
    
    if [ -z "$version" ]; then
        print_error "无法获取Python版本信息"
        return 1
    fi
    
    # 提取主版本号和次版本号
    local major=$(echo "$version" | cut -d. -f1)
    local minor=$(echo "$version" | cut -d. -f2)
    
    # 检查版本是否>=3.11
    if [ "$major" -lt 3 ] || ([ "$major" -eq 3 ] && [ "$minor" -lt 11 ]); then
        print_error "Python版本过低: $version (需要 >= 3.11)"
        return 1
    fi
    
    print_success "Python版本检查通过: $version"
    return 0
}

# 检查Python依赖
check_dependencies() {
    print_info "检查Python依赖..."
    
    local requirements_file="$PROJECT_DIR/api/requirements.txt"
    
    if [ ! -f "$requirements_file" ]; then
        print_error "依赖文件不存在: $requirements_file"
        return 1
    fi
    
    # 获取已安装的包列表
    local installed_packages=$("$PYTHON" -m pip list --format=freeze 2>/dev/null | cut -d'=' -f1 | tr '[:upper:]' '[:lower:]')
    
    # 动态读取requirements.txt文件中的所有包名
    local missing_deps=()
    
    while IFS= read -r line || [ -n "$line" ]; do
        # 跳过空行和注释行
        [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue
        
        # 提取包名（去除版本号和额外参数）
        local package=$(echo "$line" | sed -E 's/[>=<~!]=.*//; s/\[.*\]//; s/[[:space:]].*//; s/^[[:space:]]+//; s/[[:space:]]+$//')
        
        # 跳过空包名
        [ -z "$package" ] && continue
        
        # 转换为小写进行比较
        local package_lower=$(echo "$package" | tr '[:upper:]' '[:lower:]')
        local package_underscore=$(echo "$package_lower" | tr '-' '_')
        
        # 检查包是否已安装
        if ! echo "$installed_packages" | grep -qE "^(${package_lower}|${package_underscore})$"; then
            missing_deps+=("$package")
        fi
    done < "$requirements_file"
    
    if [ ${#missing_deps[@]} -gt 0 ]; then
        print_warning "缺少以下依赖 (${#missing_deps[@]}个): ${missing_deps[*]}"
        echo "是否自动安装依赖? (y/n)"
        read -r answer
        if [ "$answer" = "y" ]; then
            if install_dependencies; then
                print_success "依赖安装完成"
                return 0
            else
                print_error "依赖安装失败"
                return 1
            fi
        else
            print_error "请手动安装依赖: $PYTHON -m pip install -r $requirements_file"
            return 1
        fi
    else
        print_success "所有依赖已安装"
        return 0
    fi
}

# 安装依赖
install_dependencies() {
    print_info "正在安装Python依赖..."
    
    local requirements_file="$PROJECT_DIR/api/requirements.txt"
    
    if "$PYTHON" -m pip install -r "$requirements_file"; then
        print_success "依赖安装成功"
        return 0
    else
        print_error "依赖安装失败"
        return 1
    fi
}

# 检查 screen 是否安装
check_screen() {
    if ! command -v screen &> /dev/null; then
        print_warning "Screen 未安装，正在安装..."
        yum install -y screen
        if [ $? -ne 0 ]; then
            print_error "Screen 安装失败，请手动安装: yum install screen"
            exit 1
        fi
        print_success "Screen 安装成功"
    fi
}

# 检查服务状态
check_status() {
    local session_name=$1
    screen -list | grep -q "$session_name"
    return $?
}

# 启动主服务
start_main() {
    if check_status "$MAIN_SESSION"; then
        print_warning "主服务已在运行中"
        return
    fi
    
    print_info "启动主服务..."
    cd "$PROJECT_DIR"
    screen -dmS "$MAIN_SESSION" "$PYTHON" "$MAIN_SERVER_SCRIPT"
    sleep 2
    
    if check_status "$MAIN_SESSION"; then
        print_success "主服务启动成功"
    else
        print_error "主服务启动失败"
    fi
}

# 停止主服务
stop_main() {
    if ! check_status "$MAIN_SESSION"; then
        print_warning "主服务未运行"
        return
    fi
    
    print_info "停止主服务..."
    screen -S "$MAIN_SESSION" -X quit
    sleep 1
    
    if ! check_status "$MAIN_SESSION"; then
        print_success "主服务已停止"
    else
        print_error "主服务停止失败"
    fi
}

# 重启主服务
restart_main() {
    print_info "重启主服务..."
    stop_main
    sleep 1
    start_main
}

# 查看主服务
view_main() {
    if ! check_status "$MAIN_SESSION"; then
        print_warning "主服务未运行"
        return
    fi
    
    print_success "连接到主服务 (按 Ctrl+A 然后按 D 退出)"
    sleep 1
    screen -r "$MAIN_SESSION"
}

# 启动同步服务
start_sync() {
    if check_status "$SYNC_SESSION"; then
        print_warning "同步服务已在运行中"
        return
    fi
    
    print_info "启动同步服务..."
    cd "$PROJECT_DIR"
    screen -dmS "$SYNC_SESSION" "$PYTHON" "$SYNC_SERVER_SCRIPT"
    sleep 2
    
    if check_status "$SYNC_SESSION"; then
        print_success "同步服务启动成功"
    else
        print_error "同步服务启动失败"
    fi
}

# 停止同步服务
stop_sync() {
    if ! check_status "$SYNC_SESSION"; then
        print_warning "同步服务未运行"
        return
    fi
    
    print_info "停止同步服务..."
    screen -S "$SYNC_SESSION" -X quit
    sleep 1
    
    if ! check_status "$SYNC_SESSION"; then
        print_success "同步服务已停止"
    else
        print_error "同步服务停止失败"
    fi
}

# 重启同步服务
restart_sync() {
    print_info "重启同步服务..."
    stop_sync
    sleep 1
    start_sync
}

# 查看同步服务
view_sync() {
    if ! check_status "$SYNC_SESSION"; then
        print_warning "同步服务未运行"
        return
    fi
    
    print_success "连接到同步服务 (按 Ctrl+A 然后按 D 退出)"
    sleep 1
    screen -r "$SYNC_SESSION"
}

# 查看实时日志
view_real_time_log() {
    local log_type=$1
    local log_file="$PROJECT_DIR/runtime/logs/${log_type}.log"

    if [ ! -f "$log_file" ]; then
        print_error "日志文件不存在: $log_file"
        return
    fi

    print_info "查看 ${log_type} 日志 (动态查看最后50行, Ctrl+C退出)"
    sleep 1
    tail -f -n 50 "$log_file"
}

# 显示服务状态
show_status() {
    echo "=========================================="
    
    # 显示Python版本信息
    if command -v "$PYTHON" &> /dev/null || [ -f "$PYTHON" ]; then
        local py_version=$("$PYTHON" --version 2>&1 | grep -oP '\d+\.\d+\.\d+' | head -1)
        if [ -n "$py_version" ]; then
            echo "Python版本: $py_version($PYTHON)"
        fi
    fi
    
    if check_status "$MAIN_SESSION"; then
        echo -e "● 主服务 (FastAPI): ${GREEN}运行中${NC}"
    else
        echo -e "● 主服务 (FastAPI): ${RED}已停止${NC}"
    fi
    
    if check_status "$SYNC_SESSION"; then
        echo -e "● 同步服务: ${GREEN}运行中${NC}"
    else
        echo -e "● 同步服务: ${RED}已停止${NC}"
    fi
    
    netstat -tlnp 2>/dev/null | grep ":9999" || ss -tlnp 2>/dev/null | grep ":9999" || echo "  端口 9999 未监听"
    echo "=========================================="
    echo ""
}

# 主菜单
main_menu() {
    while true; do
        clear
        echo -e "${BLUE}================================${NC}"
        echo -e "${BLUE}   邮件服务管理系统 (Screen)${NC}($PROJECT_DIR)"
        show_status
        echo "操作菜单"
        echo "=========================================="
        echo "【主服务管理】"
        echo "  1. 启动主服务    2. 停止主服务"
        echo "  3. 重启主服务    4. 查看主服务"
        echo "【同步服务管理】"
        echo "  5. 启动同步服务  6. 停止同步服务"
        echo "  7. 重启同步服务  8. 查看同步服务"
        echo "【批量操作】"
        echo "  9. 启动所有服务  10. 停止所有服务"
        echo "  11. 重启所有服务"
        echo "【实时文件日志】"
        echo "  12. 查看Info日志         13. 查看Error日志"
        echo "  14. 查看Debug日志        15. 查看Sync日志"
        echo "【其他】"
        echo "  16. 安装/更新依赖"
        echo "  17. 查看所有Screen会话"
        echo "  0. 退出"
        echo "=========================================="
        read -p "请选择操作 [0-17]: " choice
        
        case $choice in
            1) start_main; sleep 2 ;;
            2) stop_main; sleep 2 ;;
            3) restart_main; sleep 2 ;;
            4) view_main ;;
            5) start_sync; sleep 2 ;;
            6) stop_sync; sleep 2 ;;
            7) restart_sync; sleep 2 ;;
            8) view_sync ;;
            9)
                start_main
                start_sync
                sleep 2
                ;;
            10)
                stop_main
                stop_sync
                sleep 2
                ;;
            11)
                restart_main
                restart_sync
                sleep 2
                ;;
            12) view_real_time_log "info"; read -p "按Enter键返回..." ;;
            13) view_real_time_log "error"; read -p "按Enter键返回..." ;;
            14) view_real_time_log "debug"; read -p "按Enter键返回..." ;;
            15) view_real_time_log "sync"; read -p "按Enter键返回..." ;;
            16)
                install_dependencies
                sleep 2
                ;;
            17)
                print_info "所有Screen会话:"
                screen -list
                sleep 3
                ;;
            0)
                print_success "再见！"
                exit 0
                ;;
            *)
                print_error "无效选择"
                sleep 2
                ;;
        esac
    done
}

# 初始化检查
init_check() {
    # 检查screen
    check_screen
    
    # 检查Python版本
    if ! check_python_version "$PYTHON"; then
        print_error "Python版本检查失败，请使用正确的Python解释器"
        echo "用法: $0 [python解释器路径]"
        echo "示例: $0 python3"
        echo "      $0 /www/server/pyporject_evn/versions/3.12.4/bin/python3"
        exit 1
    fi
    
    # 检查依赖
    if ! check_dependencies; then
        print_error "依赖检查失败，请先安装依赖"
        exit 1
    fi
}

# 处理命令行参数
handle_command() {
    case "$COMMAND" in
        start-all)
            init_check
            start_main
            start_sync
            exit 0
            ;;
        stop-all)
            check_screen
            stop_main
            stop_sync
            exit 0
            ;;
        restart-all)
            init_check
            restart_main
            restart_sync
            exit 0
            ;;
        status)
            check_screen
            show_status
            exit 0
            ;;
        "")
            # 无命令，进入交互菜单
            init_check
            main_menu
            ;;
        *)
            print_error "未知命令: $COMMAND"
            echo "可用命令: start-all, stop-all, restart-all, status"
            exit 1
            ;;
    esac
}

# 启动脚本
handle_command